package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        //jdbc 查询数据库操作
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //2.获取链接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=GMT%2B8", "root", "123456");

            //3.编写sql语句
            String sql = "select * from sys_user";

            //4.预处理sql  .var自动生成等号左边代码
            preparedStatement = conn.prepareStatement(sql);

            //5.如果有参数，设置参数

            //6.执行sql语句
            resultSet = preparedStatement.executeQuery();

            //7.如果是查询，就遍历结果/如果是增加删除和修改，判断是否成功
            while (resultSet.next()) {
                User u = new User();
                u.setId(resultSet.getInt(1));
                u.setName(resultSet.getString(2));
                u.setPass(resultSet.getString(3));
                users.add(u);
            }
            return users;
            //8.返回视图
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //8.返回视图（关闭资源）
            try {
                if (resultSet != null){
                    resultSet.close();
                }
                if (resultSet != null){
                    preparedStatement.close();
                }
                if (resultSet != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
